package controllers

import (
	beego "github.com/beego/beego/v2/server/web"
	"yh/models"
)

type YhController struct {
	beego.Controller
}
type Res struct {
	Code int         `json:"code"`
	Msg  string      `json:"msg"`
	Data interface{} `json:"data"`
}

func (c *YhController) Add() {
	book := c.GetString("book")
	author := c.GetString("author")
	img := c.GetString("img")
	cut := c.GetString("cut")
	yh := models.Yh{
		Book:   book,
		Author: author,
		Img:    img,
		Cut:    cut,
	}
	err := models.DB.Create(&yh).Error
	if err != nil {
		c.Data["json"] = Res{
			Code: 0,
			Msg:  "添加失败",
			Data: nil,
		}
		c.ServeJSON()
		return
	} else {
		c.Data["json"] = Res{
			Code: 200,
			Msg:  "添加成功",
			Data: nil,
		}
		c.ServeJSON()
		return
	}
}

func (c *YhController) Limit() {
	query := models.DB.Model(models.Yh{})
	name := c.GetString("name")
	if name != "" {
		query = query.Where("name like ?", "%"+name+"%")
	}
	var yh []models.Yh
	err := models.DB.Find(&yh).Error
	if err != nil {
		c.Data["json"] = Res{
			Code: 0,
			Msg:  "查询失败",
			Data: nil,
		}
		c.ServeJSON()
		return
	} else {
		c.Data["json"] = Res{
			Code: 200,
			Msg:  "查询成功",
			Data: yh,
		}
		c.ServeJSON()
		return
	}

}
func (c *YhController) Del() {
	id, _ := c.GetInt("id")
	err := models.DB.Delete(&models.Yh{}, id).Error
	if err != nil {
		c.Data["json"] = Res{
			Code: 0,
			Msg:  "删除失败",
			Data: nil,
		}
		c.ServeJSON()
		return
	} else {
		c.Data["json"] = Res{
			Code: 200,
			Msg:  "删除成功",
			Data: nil,
		}
		c.ServeJSON()
		return
	}
}
